package com.tangding.hprose.api.server.command.impl.role;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.base.Strings;
import com.tangding.common.exception.GException;
import com.tangding.common.tools.ErrorConstants;
import com.tangding.common.utils.DateUtils;
import com.tangding.common.utils.JacksonUtil;
import com.tangding.hprose.api.server.command.Command;
import com.tangding.hprose.api.server.command.Response;
import com.tangding.service.dao.role.RoleRepository;
import com.tangding.service.entity.role.Role;

/**
 * @description 
 *
 * @author Ranger
 * @version 2017年12月1日_下午8:48:58
 *
 */
@Component
public class AddRole implements Command{
	
	@Autowired
	RoleRepository roleRepository;

	@Override
	public Response exe(Object... params) throws GException {
		Role role = new Role();
		String selectItemIdStr = JacksonUtil.get(params[0], "cid.selectItem.id", true);
		if (Strings.isNullOrEmpty(selectItemIdStr)) {
			throw new GException(ErrorConstants.ERR_ILLEGAL_REQUEST);
		}
		role.setRoleId(DateUtils.getNow());
		role.setpRoleId(Integer.parseInt(selectItemIdStr));
		role.setRoleName(JacksonUtil.get(params[0], "newName", true));
		
		
		String permissionStr = JacksonUtil.get(params[0], "permissions", true);
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> permissionsRequire = JacksonUtil.readValue(permissionStr, List.class);
		List<Integer> permissionIds = new ArrayList<>();
		permissionsRequire.forEach(permission -> {
			if ((Boolean)(permission.get("isChecked"))) {
				permissionIds.add(Integer.parseInt(permission.get("id").toString()));
			}
		});
		if (permissionIds.size() > 0) {
			role.setPermission(permissionIds);
		}
		
		roleRepository.addRole(role);
		
		return doResponseSucc();
	}

}
